"""
上报接口模块
"""
import time
import uuid
import json
import logging
import requests
from typing import List, Dict, Any, Optional
from reqapi.api import BaseApi, ApiConfig
from reqapi.models.track_report import (
    TrackReportRequest, TrackLog, LogData, PageViewData, EventData,
    create_page_view_log, create_event_log, generate_random_logs
)

logger = logging.getLogger(__name__)

class TrackReportApi(BaseApi):
    """上报接口"""
    
    def __init__(self, device_id: str = None, device_token: str = None, 
                 auth_token: str = "", uk: str = ""):
        """初始化上报接口
        
        Args:
            device_id: 设备ID
            device_token: 设备令牌，如果不传则使用device_id
            auth_token: 授权令牌
            uk: uk值
        """
        device_token = device_token or device_id
        super().__init__(device_token, device_id, auth_token, uk)
        
    def report(self, user_id: str) -> bool:
        """上报数据

        Args:
            user_id: 用户ID

        Returns:
            bool: 是否上报成功
        """
        try:
            # 自动生成随机日志
            log_list = generate_random_logs(
                device_id=self.device_id,
                user_id=user_id
            )
            # 构造请求数据
            request = TrackReportRequest(
                logList=log_list,
                Sessionid=self.device_id
            )
            data = request.to_dict()
            # 获取基础请求头并添加当前请求的特定字段
            headers = self.common_headers.copy()
            headers.update({
                "content-length": str(len(json.dumps(data))),
                "tracktoken": self._generate_track_token()
            })
            print(f"请求头: {json.dumps(headers, indent=2, ensure_ascii=False)}")
            print(f"请求数据: {json.dumps(data, indent=2, ensure_ascii=False)}")
            # 统一用拦截器处理请求和响应
            response = self.interceptor.send_request(
                f"{self.BASE_URL}/api/youpin/track/auth/report",
                headers=headers,
                json=data,
                need_encrypt=False
            )
            # 兼容返回dict或response对象
            if isinstance(response, dict):
                response_json = response
            elif hasattr(response, 'json'):
                response_json = response.json()
            else:
                response_json = response
            print(f"响应内容: {json.dumps(response_json, indent=2, ensure_ascii=False)}")
            if response_json.get("code") == 0:
                logger.debug("上报成功")
                return True
            else:
                logger.error(f"上报失败，错误码：{response_json.get('code')}")
                return False
        except Exception as e:
            logger.error(f"上报时发生错误: {str(e)}")
            return False
            
    def _generate_track_token(self) -> str:
        """生成track token
        
        Returns:
            str: track token
        """
        import hashlib
        import time
        
        # 使用时间戳和随机数生成token
        timestamp = str(int(time.time() * 1000))
        random_str = str(uuid.uuid4()).replace("-", "")
        
        # 计算MD5
        md5 = hashlib.md5()
        md5.update(f"{timestamp}{random_str}".encode())
        return md5.hexdigest()


if __name__ == "__main__":
    # 测试上报
    from com.db.order_account_manager import OrderAccountManager
    account_manager = OrderAccountManager()
    account = account_manager.get_account_by_id(1)
            
    if not account:
        print("无法获取ID为1的账号")
        import sys
        sys.exit(1)
            
    device_id = account.get('device_id', '')
    auth_token = account.get('uu_token', '')
    uk = account.get('uk', '')
    
    # 创建API实例
    api = TrackReportApi(device_id=device_id, auth_token=auth_token, uk=uk)
    
    
    
    # 测试上报
    success = api.report("9975453")
    print(f"上报{'成功' if success else '失败'}")
